import {
  addCart,
  getCart,
  deleteCart,
  checkAllBook,
  changeCartStatus,
} from "@/Api/cart";
const state = {
  cart: [],
};
const mutations = {
  ADD_CART(state, book) {
    state.cart = book;
  },
  //传递的book是一个数组的index
  REMOVE_CART(state, index) {
    state.cart.splice(index, 1);
    // 删除
    console.log(state.cart);
  },
  // 修改cart的选中状态
  CHANGE_SELECTED(state, { index, status }) {
    state.cart[index].isChecked = status;
  },
  CHANGE_SELECTED_ALL(state, status) {
    state.cart.forEach((item) => {
      item.isChecked = status;
    });
  },
};
const actions = {
  async ckeckBook(context, index) {
    let status = context.state.cart[index].isChecked ? 0 : 1;
    let id = context.state.cart[index].id;
    let result = await changeCartStatus({ status, id });
    console.log(result);
    if (result.data.status == 200) {
        context.commit("CHANGE_SELECTED", { index, status });
      return "success";
    } else {
      return "error";
    }
  },
  async checkAllBook(context, status) {
    let result = await checkAllBook(status);
    if (result.data.status == 200) {
      context.commit("CHANGE_SELECTED_ALL", status);
      return "success";
    } else {
      return "error";
    }
  },
  async addCart(context, data) {
    //如果购物车中含有这本书，则返回不允许添加
    if (context.state.cart.some((item) => data.bookId == item.bookId))
      return "error";
    let result = await addCart(data);
    console.log(result);
    if (result.data.status == 200) {
      context.dispatch("getCart");
    }
  },
  getCart({ commit }) {
    getCart().then((res) => {
      if (res.data.status == 200) commit("ADD_CART", res.data.data);
    });
  },
  async deleteCart(context, index) {
    let result = await deleteCart(context.state.cart[index].id);
    if (result.data.status == 200) {
      context.commit("REMOVE_CART", index);
      return "success";
    } else return "error";
  },
};
const getters = {
  checkBook(state) {
    return function (id) {
      return state.cart.some((book) => book.bookId === id);
    };
  },
  cartNum(state) {
    return state.cart.length;
  },
};
export default {
  state,
  mutations,
  actions,
  getters,
};
